package br.com.searchpeople.asynctask;

import java.io.IOException;

import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import br.com.searchpeople.activity.TimelineActivity;
import br.com.searchpeople.database.SingletonPostBD;
import br.com.searchpeople.model.PostModel;

import com.savagelook.android.UrlJsonAsyncTask;

public class PostTask extends UrlJsonAsyncTask {
	
	private String name;
	private String description;
	private String country;
	private String state;
	private String city;
	private String phone;
	private String email;
	private String image;
	private double latitude;
	private double longitude;
	private int user_id;
	private String date;
	
	private Context context;
	public PostTask(Context context, String name, String description, String country, String state, String city,
			String phone, String email, String image, double latitude, double longitude) {
		super(context);
		this.city = city;
		this.name = name;
		this.description = description;
		this.country = country;
		this.state = state;
		this.phone = phone;
		this.email = email;
		this.image = image;
		this.latitude = latitude;
		this.longitude = longitude;
		this.context = context;
	}

	@Override
	protected JSONObject doInBackground(String... urls) {
		
		SharedPreferences settings = context.getSharedPreferences("general",Context.MODE_PRIVATE);
		user_id = settings.getInt("user_id", 0);
		
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(urls[0]);
		JSONObject holder = new JSONObject();
		JSONObject postObj = new JSONObject();
		String response = null;
		JSONObject json = new JSONObject();
	
		try {
			try {
				json.put("success", false);
				json.put("info", "Alguma coisa deu erro. Tente novamente!");

				postObj.put("name", name);
				postObj.put("description", description);
				postObj.put("city", city);
				postObj.put("state", state);
				postObj.put("country", country);
				postObj.put("phone", phone);
				postObj.put("email", email);
				postObj.put("image", image);
				postObj.put("latitude", latitude);
				postObj.put("longitude", longitude);
				postObj.put("user_id", user_id);
				holder.put("post", postObj);		
				
				StringEntity se = new StringEntity(holder.toString());
				post.setEntity(se);

				post.setHeader("Accept", "application/json");
				post.setHeader("Content-Type", "application/json");

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				response = client.execute(post, responseHandler);
				json = new JSONObject(response);
				date = json.getString("data");
			} catch (HttpResponseException e) {
				e.printStackTrace();
				Log.e("ClientProtocol", "" + e);
				json.put("info",
						"Nao foi possivel cadastrar post no servidor.");
			} catch (IOException e) {
				e.printStackTrace();
				Log.e("IO", "" + e);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("JSON", "" + e);
		}
		return json;
	}

	@Override
	protected void onPostExecute(JSONObject json) {

		try {
			if (json.getBoolean("success")) {
				
				Bitmap stringToBitmap = StringToBitMap(image);
				
				PostModel post = new PostModel(name, description, country, state, city, phone, email, stringToBitmap, latitude, longitude, user_id);

				if (SingletonPostBD.getInstance(context.getApplicationContext()).addPost(post)) {
					createSpecificNotificationToast("Desaparecido cadastrado com SUCESSO!!");
				} else {
					createSpecificNotificationToast("ERRO ao cadastrar!!");
				}	
			}	
		} catch (Exception e) {
			createSpecificNotificationToast(e.getMessage());
		} finally {
			super.onPostExecute(json);
		}
	}
	
	private void createSpecificNotificationToast(String arg0) {
		Context context = this.context.getApplicationContext();
		CharSequence text = arg0;
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
	
	 public Bitmap StringToBitMap(String encodedString){
	     try{
	       byte [] encodeByte = Base64.decode(encodedString,Base64.DEFAULT);
	       Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
	       return bitmap;
	     }catch(Exception e){
	       e.getMessage();
	       return null;
	     }
	 }
}